/**
 * 页面列表公共逻辑
 */
import {
	ref,
	computed,
	unref
} from 'vue'
import {
	onReachBottom,
	onPageScroll,
	onPullDownRefresh
} from '@dcloudio/uni-app'
// import {
// 	listRiskPointManagement
// } from '@/api/riskcontrol.js'
export default function({
	queryParams = {},
	api = {},
} = {}) {
	let list = ref([]),
		total = ref(0),
		scrollTop = ref(0),
		showPopup = ref(false),
		formData = computed(() => {
			return []
		})
	const getListData = async (reachBottom) => {
		try {
			const {
				data
			} = await api.page(queryParams)
			let rows = data.rows || []
			if (reachBottom) {
				rows = [...list.value, ...rows]
			}
			list.value = rows
			total.value = data.total
		} catch (e) {
			//TODO handle the exception
		}
	}
	// 获取检查地点列表
	// let checkList = ref([])
	// const getCheckPonit = async () => {
	// 	const {
	// 		data = []
	// 	} = await listRiskPointManagement()
	// 	checkList.value = data.map((item) => ({
	// 		dictLabel: item.riskLocationName,
	// 		dictValue: item.id
	// 	}))
	// }
	// 筛选popup
	const openPopup = () => {
		showPopup.value = true
		console.log('112');
	}
	// 关闭popup事件
	const closePopup = () => {
		showPopup.value = false
	}
	// 重置查询条件
	const reset = () => {
		for (const item of formData.value) {
			queryParams[item.prop] = ''
		}
		getListData()
		showPopup.value = false
	}
	const submit = () => {
		getListData()
		showPopup.value = false
	}
	// 触底分页
	onReachBottom(() => {
		if (unref(total) > unref(list).length) {
			queryParams.pageNum += 1
		} else {
			uni.showToast({
				title: "没有更多数据了",
				icon: "none"
			});
			return false;
		}
		getListData(true)
	})
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop
	})
	// 下拉刷新
	onPullDownRefresh(() => {
		uni.startPullDownRefresh({
			success() {
				queryParams.pageNum = 1
				getListData()
				uni.stopPullDownRefresh()
			},
			fail() {
				uni.stopPullDownRefresh()
			}
		})
		uni.stopPullDownRefresh()
	})
	return {
		getListData,
		// getCheckPonit,
		total,
		scrollTop,
		// checkList,
		list,
		formData,
		showPopup,
		openPopup,
		closePopup,
		reset,
		submit
	}
}